package top.rainf.controller;

import io.swagger.models.auth.In;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.annotations.Param;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.bind.annotation.SessionAttribute;
import top.rainf.constants.AttributeConstants;
import top.rainf.domain.dto.ReplyFullInfo;
import top.rainf.domain.dto.UserFullInfo;
import top.rainf.domain.vo.*;
import top.rainf.service.*;
import top.rainf.support.Result;
import top.rainf.support.StringMatcher;
import top.rainf.support.TokenGenerator;
import top.rainf.support.VerifyUtil;
import top.rainf.util.PagerUtil;
import top.rainf.util.StringUtil;

import javax.servlet.http.HttpServletRequest;
import java.util.*;

/**
 * @author 星环
 * @date Wed May 10 21:04:41 CST 2023
 * @description 帖子的控制器类 由本人的生成器自动生成~
 */
@RestController
@Slf4j
@RequestMapping("/post")
public class PostController {
    @Autowired
    IPostService postService;

    @Autowired
    IBanRecordService banRecordService;
    @Autowired
    IAuthorityService authorityService;
    //顶部导航
    @Autowired
    IBlockService blockService;
    //用户资料卡片
    @Autowired
    IUserBaseInfoService userBaseInfoService;
    @Autowired
    IUserPersonalInfoService userPersonalInfoService;
    @Autowired
    //回复
    IPostReplyService postReplyService;

    @Autowired
    INoticeService noticeService;
    /**
    * 获取全部帖子的列表
    * @return 返回是否获取成功~
    */
    @RequestMapping("/list")
    public Result list(){
        List<Post> list = postService.getPostList();
        if(list == null){
            return Result.fail();
        }
        return Result.success().addObj("list",list);
    }

    /**
    * 根据id获取一个帖子
    * @return 返回是否获取成功~
    */
    @RequestMapping("/one")
    public Result getOnePost(int id){
        Post post = postService.getOneById(id);
        if(post == null){
                    return Result.fail();
        }
        return Result.success().addObj("data",post);
    }
    /**
    * 根据id删除一个帖子
    ---------------------------
    * @param id 要删除的帖子的id
    * @return 返回是否获取成功~
    */
    @RequestMapping("/deleteById")
    public Result deleteById(int id, int userId,
                             @SessionAttribute(AttributeConstants.LOGIN_TOKEN) String token){
        String ver = VerifyUtil.checkToken(token, userId);
        if (!StringUtil.isNullOrEmpty(ver)){
            return Result.fail("请登录后操作！");
        }
        boolean suc = postService.deleteOneById(id);
        return suc ? Result.success() : Result.fail();
    }

    @RequestMapping("/deleteByIds")
    public Result deleteByIds(List<Integer> idList){
        boolean suc = postService.deleteAll(idList);
        return suc ? Result.success() : Result.fail();
    }

    @RequestMapping("update")
    public Result update(Post post){
        boolean suc = postService.updateById(post);
        return suc ? Result.success() : Result.fail();
    }

    @RequestMapping("list-all-hot-posts")
    public Result listHotPosts(int num){
        List<Post> list = postService.getHotPost(num);
        return list == null ? Result.fail("未知错误") : Result.success().addObj("list",list);
    }

    @RequestMapping("/page")
    public Result page(@RequestParam Map<String,Object> paraMap){
        if(paraMap.containsKey("from")){
            Object from = paraMap.get("from");
            Integer iFrom = Integer.parseInt((String) from);
            paraMap.put("from",iFrom);
        }
        if(paraMap.containsKey("numPerPage")){

            Object  numPerPage = paraMap.get("numPerPage");
            Integer iNumPerPage = Integer.parseInt((String) numPerPage);
            paraMap.put("numPerPage",iNumPerPage);
        }
        List<Post> list = postService.selectByPaged(paraMap,null);
        int totalCount = postService.getTotalCountQuery(paraMap);

        int curPage1 = Integer.parseInt((String)paraMap.get("curPage"));
        int curPage = 1;
        curPage = curPage1;
        System.out.println();
        List<String> pageList = PagerUtil.getPageListStr(10,curPage ,totalCount);
        return Result.success().addObj("postList",list).addObj("pageList",pageList);
    }

    @RequestMapping("/postOne")
    public Result postOne(int userId, int blockId, int clazzId,
                          String title, String content, HttpServletRequest request){
    //    验证用户是否登录，是否禁言，版块是否存在。
    //    用户多发了一个帖子，添加发帖数，版块发帖数，分区发帖数
        String token = (String)request.getSession().getAttribute(AttributeConstants.LOGIN_TOKEN);
        String res = authorityService.checkUserLogin(token, userId);
        if (!StringUtil.isNullOrEmpty(res)) {
            return Result.fail(res);
        }
        List<BanRecord> banRec = banRecordService.getUserBannedRecordIn(blockId, userId);
        if(banRec.size() != 0){
            return Result.fail("您已被禁言！到"+banRec.get(0).getEndTime() + "，因为" + banRec.get(0).getReason());
        }


        String res1 = postService.postOne(userId, blockId, clazzId, title, content);
        if(!StringUtil.isNullOrEmpty(res1)){
            return Result.fail(res1);
        }


        sendAtMsg(content,title);

        return Result.success("发帖成功");
    }

    /**
     * 找出帖子所有@的人，尝试给他发通知
     * @param content
     * @param title
     */
    private void sendAtMsg(String content,String title) {
        //用这个@【用户名】
        String[] strings = StringMatcher.extractMatches(content, "@\\w+");
        //打算限制@5个人，意思意思。
        List<String> atUsers = new ArrayList<>(5);
        for (String string : strings) {
            atUsers.add(string.substring(1));
        }

        log.info("这些是@的人{}",atUsers.toString());
        List<Integer> idByUsernames = userBaseInfoService.getIdByUsernames(atUsers);
        for (Integer id : idByUsernames) {
            noticeService.sendTo(id,"您在帖子‘" + title + "’中被@了");

        }
    }

    @RequestMapping("/init")
    public Result init(int postId){
        Post post = postService.getOneById(postId);
        Block block = blockService.getOne(post.getBlockId());
    //    获得所有回复
        List<PostReply> replyList = postReplyService.getReplyListByPostIdPaged(postId,1,10);
    //    分页
        int totalCount = postReplyService.getReplyCountInPost(postId);
        List<String> pageList = PagerUtil.getPageListStr(10,1,totalCount);
        //发帖用户信息
        UserBaseInfo pBase = userBaseInfoService.getOneById(post.getAuthorId());
        UserPersonalInfo pMore = userPersonalInfoService.getOneById(post.getAuthorId());
        UserFullInfo userFullInfo = new UserFullInfo(pBase,pMore);
    //    用户资料卡
        Set<Integer> uidSet = new HashSet<>();
        replyList.forEach(postReply -> uidSet.add(postReply.getUserId()));
        List<Integer> uidList = uidSet.stream().toList();
        List<UserBaseInfo> baseList = userBaseInfoService.getByIds(uidList);
        List<UserPersonalInfo> moreList = userPersonalInfoService.getByIds(uidList);
        Map<Integer,Object> userMap = new HashMap<>();
        baseList.forEach(base->{
            UserFullInfo value = new UserFullInfo();
            value.setBase(base);
            userMap.put(base.getId(), value);
        });
        moreList.forEach(more->{
            UserFullInfo full = (UserFullInfo) userMap.get(more.getUserId());
            full.setMore(more);
        });
        //用户信息组装完毕
        //为每个回复组装用户信息
        List<ReplyFullInfo> replyFullInfoList = new ArrayList<>();
        replyList.forEach(reply->{
            ReplyFullInfo replyFullInfo = new ReplyFullInfo();
            replyFullInfo.setReply(reply);
            UserFullInfo user = (UserFullInfo)userMap.get(reply.getUserId());
            replyFullInfo.setUser(user);
            replyFullInfoList.add(replyFullInfo);
        });
        Result result = Result.success().addObj("post", post)
                .addObj("posterInfo",userFullInfo)
                .addObj("block", block)
                .addObj("pageList", pageList)
                .addObj("replyList", replyFullInfoList);
        log.info(result.toString());
        return result;
    }


    @RequestMapping("simpleMsgList")
    public Result simpleMsgList(int nowPage,int numPerPage,@SessionAttribute(AttributeConstants.LOGIN_TOKEN)String token){
        int userId = TokenGenerator.getUserIdFromToken(token);
        if(userId == -1){
            return Result.fail("您还未登录！");
        }
        List<Post> postList = postService.getUserSimplePostListPaged(userId,nowPage,numPerPage);
        int total = postService.getTotalCountOfUser(userId);
        List<String> pageList = PagerUtil.getPageListStr(numPerPage,nowPage,total);
        return Result.success()
                .addObj("postList",postList)
                .addObj("pageList",pageList);
    }
}
